<template>
  <div class="add-child-component-popup">
    <el-dialog
      v-model="dialogVisible"
      :title="$demoi18n('common.addSubcomponent')"
      append-to-body
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :class="`${visualThemeClassName} ${xvueNameSpace}`"
      width="300px"
      @close="canelDialog()"
    >
      <el-form
        ref="form"
        :model="form"
      >
        <VsFormItem
          :form="form"
          path="name"
          :confs="fItemConf"
          label-width="100px"
          required
        />
        <VsFormItem
          :form="form"
          label-width="100px"
          path="compKey"
          :confs="fItemConf"
        />
      </el-form>
      <template #footer>
        <span>
          <el-button
            size="default"
            @click="canelDialog()"
          >{{ $demoi18n('btn.cancel') }}</el-button>
          <el-button
            type="primary"
            size="default"
            @click="saveDialog()"
          >
            {{ $demoi18n('btn.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import formMixin from '@/mixin/form-mixin.js';
import childComponents from './child-components.js';
export default {
  components: { VsFormItem },
  mixins: [formMixin],
  props: {},
  emits: ['add-child-component'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      dialogVisible: false,
      form: {
        id: '',
        name: '',
        compKey: '',
        config: null,
      },
    };
  },
  computed: {
    fItemConf() {
      const fItemConf = {
        name: {
          label: this.$demoi18n('common.componentName'),
          type: 'text',
          required: true,
        },
        compKey: {
          label: this.$demoi18n('common.componentType'),
          type: 'enum',
          options: childComponents,
        },
      };
      return fItemConf;
    },
  },
  watch: {
    'form.compKey'(compKey) {
      const item = childComponents.find(n => n.value === compKey);
      this.form.name = item.label;
    },
  },
  methods: {
    openDialog() {
      this.form = {
        id: Date.now(),
        name: this.$demoi18n('components.name.hoverText'),
        compKey: 'hover-text',
        config: null,
      };
      this.dialogVisible = true;
    },
    async saveDialog() {
      const isTrue = await this.validChildForms();
      if (!isTrue) {
        return;
      }

      const config = await import(`../../${this.form.compKey}/config/config.js`);
      this.form.config = config.default;
      const form = JSON.parse(JSON.stringify(this.form));
      this.$emit('add-child-component', form);
      this.dialogVisible = false;
    },
    canelDialog() {
      this.dialogVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
</style>
